using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;


namespace Framework.Input
{
    public sealed class InputManager : FrameworkModule
    {
        public override bool NeedUpdate => true;

        private Dictionary<KeyCode, List<FrameworkAction>> m_KeyCode2Action = new Dictionary<KeyCode, List<FrameworkAction>>();
        private List<KeyCode> m_ListenKeyCode = new List<KeyCode>();

        public override void Init()
        {
        }

        public override void Update(float elapseSeconds, float realElapseSeconds)
        {
            for (int i = 0; i < this.m_ListenKeyCode.Count; i++)
            {
                KeyCode code = this.m_ListenKeyCode[i];
                if (UnityEngine.Input.GetKeyDown(code))
                {
                    this.BroadCastCodeEvent(code);
                }
            }
        }

        public void AddKeyCodeListener(KeyCode code,FrameworkAction action)
        {
            List<FrameworkAction> listAction;
            if (!this.m_KeyCode2Action.TryGetValue(code, out listAction))
            {
                listAction = new List<FrameworkAction>();
                this.m_KeyCode2Action[code] = listAction;
            }
            if (listAction.Count == 0)
            {
                this.m_ListenKeyCode.Add(code);
            }
            listAction.Add(action);
        }

        public void DelKeyCodeListener(KeyCode code,FrameworkAction action)
        {
            List<FrameworkAction> listAction;
            if (!this.m_KeyCode2Action.TryGetValue(code, out listAction))
            {
                return;
            }
            listAction.Remove(action);
            if (listAction.Count == 0)
            {
                this.m_ListenKeyCode.Remove(code);
            }
        }

        private void BroadCastCodeEvent(KeyCode code)
        {
            List<FrameworkAction> listAction = this.m_KeyCode2Action[code];
            if (listAction.Count > 0)
            {
                listAction[listAction.Count - 1].Invoke();
            }
        }
    }
}